/**
 * 2017年2月21日
 * 疯狂赛车 Handler
 */

var roomManager = require('../../../services/fksc/roomManager');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

handler.bid = function (msg, session, next) {
    console.log('fksc gameHandler.bid caught >>>>>>>>>>>>>>>>>>>>');
    console.log(msg);

    var gameId = session.get('gameId');
    var roomId = session.get('roomId');
    var playerId = session.get('playerId');

    var err = '';

    for (var k in msg) {
        if (isNaN(k)) {
            delete msg[k];
            continue;
        }
        if (parseInt(k) > 8 || parseInt(k) < 0) {
            err = '下注位置有误！';
        }
        msg[k] = (parseInt(msg[k]) * 100);  // 元转化为分
    }

    if (err) {
        next(null, { err });
        return;
    }

    var ret = roomManager.bid(roomId, playerId, msg);

    next(null, { ret });
};

handler.applyBanker = function (msg, session, next) {
    console.log('fksc gameHandler.applyBanker caught >>>>>>>>>>>>>>>>>>>>');
    console.log(msg);

    var roomId = session.get('roomId');
    var playerId = session.get('playerId');

    if (playerId != msg.playerId || roomId != msg.roomId) {
        next(null, { err: 'id can not match' });
        return;
    }

    roomManager.applyBanker(msg, function (data, rel) {
        console.log(data);

        var ret = {};
        if (!rel) {
            ret = data;
        }
        next(null, ret);
    });
};


handler.cancelBanker = function (msg, session, next) {
    console.log('fksc gameHandler.cancelBanker caught >>>>>>>>>>>>>>>>>>>>');
    console.log(msg);

    var roomId = session.get('roomId');
    var playerId = session.get('playerId');

    if (playerId != msg.playerId || roomId != msg.roomId) {
        next(null, { err: 'id can not match' });
        return;
    }

    roomManager.cancelBanker(msg, function (data, rel) {
        console.log(data);

        var ret = {};
        if (!rel) {
            ret = data;
        }
        next(null, ret);
    });
};

handler.cutInBanker = function (msg, session, next) {
    next(null, {});
};
